<template>
  <div>
  <ag-grid-vue class="ag-theme-balham"
               v-bind="props"
			   :columnDefs="columnDefs"
               :rowData="rowData"
               :style="style"
               @rowSelected="handleSelectionChange"
               @rowClicked="handleRowClicked"
               :defaultColDef="defaultColDef"
  >
  </ag-grid-vue>

  <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
  />
  </div>
</template>

<script lang="ts" setup>
import eventBus from '@/event/eventBus';
import {onMounted, ref, onUnmounted, watch, computed, inject} from "vue";
import {
  queryListResultKey,executeQueryKey,totalKey,queryParamKey,loadingKey,tableRowSelectChangeKey
  ,setRowDataKey
} from "@/config/app.keys";
import { AgGridVue } from "ag-grid-vue3";
import { formModeKey,vFormSchemeKey } from "@/components/form/state.key";
import { generateMd5 } from "@/utils/crypto.js";
import {listCombination} from "@/api/business/extmodelfieldmetadatatag";

interface Props {
  checkboxSelection?:boolean //设置数据复选框
  headerCheckboxSelection?:boolean  //表头是否也显示复选框，用于全选反选用
  rowSelection?: string //设置多行选中 ，若是single
  rowHeight?:string//行高
  width?:string//列宽
  columnDefs:object
  style?:any
  dataSourceType?:string//数据源类型：input(手工录入),bindcomponent(绑定组件)
  rowData?:object//行数据
  bindComponent?:string
  rowSelectTriggerComponents?:string//行选择触发组件，通知组件进行处理
  tableHeight?:string
  tableWidth?:string
}

const props = defineProps<Props>()

interface Emits {
  // (e: 'changeColumnDefs', v: object): void
  (e: 'changeRowData', v: object): void
}

const tagOptions = ref<any[]>([])
const emits = defineEmits<Emits>()
const defaultColDef = ref({
  // suppressEnterToBatchSort: true,
  singleClickEdit:true
});
const rowData = ref([]);
const total = ref(0);
const loading = ref(false)
const ids=ref([])
const selectRows=ref([])
const single = ref(true);
const multiple = ref(true);
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
})
const columnDefs =ref([])
const formMode = inject(formModeKey)
const cMode = computed<FormFieldMode>(() => {
  if (props.mode) {
    return props.mode
  }
  if (formMode?.value) {
    return formMode.value
  }
  return "edit"
})
const isTagOptionsLoaded = ref(false)
watch(()=>props,async (val) => {
  if (!isTagOptionsLoaded.value) {
    try {
      const res = await listCombination()
      tagOptions.value = res.data || []
      isTagOptionsLoaded.value = true // 标记已加载
    } catch (error) {
      console.error('Failed to load tagOptions:', error)
      isTagOptionsLoaded.value = true // 即使失败也标记为已尝试加载
    }
  }
  columnDefs.value = makeColumnDefs(props.columnDefs)
  console.log('AgGrid Table convert to columnDefs:' + JSON.stringify(columnDefs.value));
  //手工录入数据
  if (props.dataSourceType === 'input') {
    rowData.value = props.rowData
    emits('changeRowData', rowData.value)
  } else {
    //监控数据变化,来自其他组件数据不需保存
    let prefix = getBusKeyPrefix();
    eventBus.$on(prefix + queryListResultKey, (data) => {
      rowData.value = data;
      //清空选择
      selectRows.value = []
      ids.value = []
    })
    eventBus.$on(prefix + totalKey, (data) => {
      total.value = data;
    })
    eventBus.$on(prefix + queryParamKey, (data) => {
      console.log('queryParamKey:' + JSON.stringify(data.value));
      queryParams.value = data.value;
    })
    eventBus.$on(prefix + loadingKey, (data) => {
      loading.value = data;
    })

  }
},{immediate:true,deep:true})

/**
 * 根据id查找标签名称
 * @param headerName
 */
function getTagName(headerName) {
  const selectedOption = tagOptions.value.find(opt => opt.id === headerName)

  // 如果找到选项且有fieldEnName属性，则回填到字段名称
  if (selectedOption && selectedOption.combinationName) {
    //返回.后面字符串
    if (selectedOption.combinationName.indexOf('.') > -1) {
      return selectedOption.combinationName.substring(selectedOption.combinationName.indexOf('.') + 1)
    }else {
      return selectedOption.combinationName
    }
  }else{
    return headerName;
  }
}

//构造列定义
function makeColumnDefs(columnDefs){
  let newColumnDefs=[];

  for(let i=0;i<columnDefs.length;i++){
    let cloneColumnDef = JSON.parse(JSON.stringify(columnDefs[i]));
    //替换headerName为标签名称(原来是id)
    cloneColumnDef.headerName = getTagName(cloneColumnDef.headerName);
     //判断自定义渲染器是否为
	  newColumnDefs.push(Object.assign({}, cloneColumnDef));
	 if(newColumnDefs[i].cellRenderer==='WrapColumnDesignNestedDragItem'){
	    newColumnDefs[i].cellRenderer='WrapNestedDragItem'
	 }
  }
  return newColumnDefs;
}
const style = computed(
    () => {
      let tableHeight='300px';
      if(props.tableHeight){
        tableHeight = props.tableHeight;
      }
      let tableWidth='400px';
      if(props.tableWidth){
        tableWidth = props.tableWidth;
      }
      return 'height:'+tableHeight+';width:'+tableWidth+';';
    }
);
/**
 * 获取bus监控key前缀
 */
function getBusKeyPrefix(){
  return props.bindComponent+"_"
}

onMounted(async () => {
  eventBus.$emit(getBusKeyPrefix() + executeQueryKey, queryParams.value);

})
onUnmounted(() =>{
  //如果绑定了组件，则撤销监控
  if(cMode.value!=='design') {
    if (props.dataSourceType === 'bindcomponent') {
      let prefix = getBusKeyPrefix();
      eventBus.$off(prefix + queryListResultKey);
      eventBus.$off(prefix + totalKey);
      eventBus.$off(prefix + queryParamKey);
      eventBus.$off(prefix + loadingKey);
    }
  }
})
function getList() {
  let prefix = getBusKeyPrefix();
  eventBus.$emit(prefix+executeQueryKey,queryParams.value);
}

// 多选框选中数据
function handleSelectionChange(params) {

  //debugger;

  selectRows.value = params.api.getSelectedRows();
  // single.value  = (selectRows.value.length==1)
  // multiple.value = (selectRows.value.length>1)
  // 触发行选中事件
  let items = props.rowSelectTriggerComponents.split(",")
  let i=0;
  for(i=0;i<items.length;i++){
    let item = items[i];
    let prefix = item+"_"
    eventBus.$emit(prefix+tableRowSelectChangeKey, {selectRows:selectRows.value})
  }

}
// 处理行点击事件
function handleRowClicked(params) {
  console.log('Clicked row data:', params.data);
  //触发事件setRowDataKey
  eventBus.$emitVague("_"+setRowDataKey,params.data)
}
/**
 * 判断是否含有自定义渲染列
 * @param columnDefs
 */
function isHaveCustomRenderColumn(columnDefs1){
  console.log('isHaveCustomRenderColumn,columnDefs1:'+JSON.stringify(columnDefs1))
  for(let i=0;i<columnDefs1.length;i++){
    if(columnDefs1[i].cellRenderer){
      return true;
    }
  }
  return false;
}
</script>



<style scoped>

</style>
